<template>
	<div class="app-container">
    <div class="filter-container tw-filter">
      <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-edit" v-has="$store.state.user.btn_common+'add'" @click="handleAdd()">添加</el-button>

      <el-input v-model="queryList.real_name" placeholder="请输入姓名" class="filter-item tw-filter-input" clearable />
      <el-input v-model="queryList.mobile" placeholder="请输入手机号码" class="filter-item tw-filter-input"  clearable />
      <el-input v-model="queryList.email" placeholder="请输入Email" class="filter-item tw-filter-input" clearable />

      <el-select v-model="queryList.unit_id" class="filter-item tw-filter-input" placeholder="请选择单位" filterable clearable v-if="$store.state.user.adminInfo.unit_id == 0">
      	<el-option v-for="item in unitListAll" :key="item.id" filter="false" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <!-- <el-cascader placeholder="请选择部门" class="filter-item tw-filter-input" style="width: 240px; margin-right:10px"
      	v-model="queryList.dep_id" clearable :options="departmentListAll"
      	:props="{ checkStrictly: true, expandTrigger: 'hover', value:'id', label:'name', emitPath: false}" separator=" > "
      >
      </el-cascader> -->

      <el-select v-model="queryList.duties_id" class="filter-item tw-filter-input" placeholder="请选择职位" clearable>
      	<el-option v-for="item in dutiesListAll" :key="item.id" filter="false" :label="item.name" :value="item.id"></el-option>
      </el-select>

      <el-select v-model="queryList.groups_id" class="filter-item tw-filter-input" placeholder="请选择权限组" clearable>
      	<el-option v-for="item in groupsListAll" :key="item.id" filter="false" :label="item.name" :value="item.id"></el-option>
      </el-select>

      <el-select v-model="queryList.state" class="filter-item tw-filter-input" placeholder="请选择状态" clearable>
      	<el-option key="" label="全部状态" value="" />
      	<el-option key="1" label="启用" value="1" />
      	<el-option key="0" label="禁用" value="0" />
      </el-select>

      <!-- <el-input v-model="queryList.member_id" placeholder="请输入绑定用户ID" class="filter-item tw-filter-input" clearable />
      <el-input v-model="queryList.member_name" placeholder="请输入绑定用户名" class="filter-item tw-filter-input" clearable />
      <el-select v-model="queryList.is_member" class="filter-item tw-filter-input" placeholder="请选择是否绑定用户" clearable>
      	<el-option key="" label="全部" value="" />
      	<el-option key="1" label="绑定" value="1" />
      	<el-option key="0" label="未绑定" value="0" />
      </el-select> -->

      <el-button v-waves class="filter-item tw-filter-button" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

		<!-- 表格内容 -->
    <el-table
      v-loading="listLoading"
      :data="tableList"
      @selection-change="handleSelectionChange"
      border fit highlight-current-row style="width: 100%;"
    >
      <!-- <el-table-column type="selection" width="50" /> -->
      <el-table-column label="ID" prop="id" align="center" width="50" />
      <el-table-column label="姓名" prop="real_name" align="center" />
      <el-table-column label="手机号码" prop="mobile" align="center" />
      <el-table-column label="单位" prop="unit_name" align="left" />
      <!-- <el-table-column label="部门" prop="dep_name" align="center" /> -->
      <el-table-column label="职位" prop="duties_name" align="center" />
      <el-table-column label="权限组" prop="groups_name" align="center" />
      <el-table-column label="Email" prop="email" align="center" />
      <!-- <el-table-column label="QQ" prop="qq" align="center" /> -->
      <!-- <el-table-column label="绑定用户ID" align="center">
        <template slot-scope="{row}">
          <span v-if="row.member_id">{{row.member_id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定用户名" align="center">
        <template slot-scope="{row}">
          <span v-if="row.member_id">{{row.member_name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定用户姓名" align="center">
        <template slot-scope="{row}">
          <span v-if="row.member_real_name">{{row.member_real_name}}</span>
          <span v-else>未绑定用户</span>
        </template>
      </el-table-column>
      <el-table-column label="是否接收信息提醒" align="center">
        <template slot-scope="{row}">
          <span v-if="row.is_receive_remind">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column> -->
      <el-table-column label="添加时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.add_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.login_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录次数" prop="login_num" align="center" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span v-if="row.state == 1">启用</span>
          <span v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" v-has="$store.state.user.btn_common+'edit'" @click="handleEdit(row.id)">编辑</el-button>
          <div style="display:inline-block;margin: 0 10px" v-if="!row.is_super">
            <el-button size="mini" v-has="$store.state.user.btn_common+'upshow'" v-if="row.state" @click="handleUpshow(row.id)">禁用</el-button>
            <el-button size="mini" v-has="$store.state.user.btn_common+'show'"  v-else @click="handleShow(row.id)">启用</el-button>
          </div>
          <el-button size="mini" v-if="!row.is_super" v-has="$store.state.user.btn_common+'del'" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
		</el-table>
		<pagination v-show="isPage && listTotal > 0" :total="listTotal" :page.sync="queryList.curpage" :limit.sync="queryList.page" @pagination="getList" />

    <!-- 添加/编辑 -->
    <el-dialog width="40%" @close="resetForm()" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
     <el-form label-position="right" label-width="120px" ref="dataForm" :rules="rules" :model="form">
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="form.real_name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="所属单位" prop="unit_id" v-if="$store.state.user.adminInfo.unit_id == 0">
          <el-select v-model="form.unit_id" placeholder="请选择所属单位" style="width: 100%" clearable filterable>
            <el-option v-for="item in unitList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="所属部门" prop="dep_id">
        	<el-cascader placeholder="请选择所属部门" v-model="form.dep_id" :options="departmentList"
        		:props="{ checkStrictly: false, expandTrigger: 'hover', value: 'id', label: 'name', emitPath:false}"
        		separator="> " style="width: 100%"></el-cascader>
        </el-form-item> -->
        <el-form-item label="职位" prop="duties_id">
        	<el-select v-model="form.duties_id" class="filter-item" placeholder="请选择职位" style="display:block;" filterable>
        		<el-option v-for="item in dutiesList" :key="item.id" filter="false" :label="item.name" :value="item.id" />
        	</el-select>
        </el-form-item>
        <el-form-item label="权限组" prop="groups_id" v-if="!form.is_super">
        	<el-select v-model="form.groups_id" class="filter-item" placeholder="请选择权限组" style="display:block;" filterable>
        		<el-option v-for="item in groupsList" :key="item.id" filter="false" :label="item.name" :value="item.id" />
        	</el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item v-if="dialogStatus == 'create'" label="登录密码" prop="password">
          <el-input v-model="form.password" show-password placeholder="6到20位之间" />
          <p class="tw-tip-text">数组、字母、下划线组成，6到 20位之间</p>
        </el-form-item>
        <el-form-item v-else label="登录密码">
          <el-input v-model="form.password" show-password placeholder="不修改则为空" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" type="email" placeholder="请输入邮箱" />
        </el-form-item>

        <!-- <el-form-item label="QQ" prop="qq">
          <el-input v-model="form.qq" placeholder="请输入QQ号码" />
        </el-form-item> -->

        <!-- <el-form-item label="是否接收信息提醒">
          <el-radio-group v-model="form.is_receive_remind">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="绑定用户ID" prop="member_id">
          <el-input v-model="form.member_id" placeholder="请输入绑定用户ID" />
        </el-form-item>
        <el-form-item label="绑定用户名" prop="member_name">
          <el-input v-model="form.member_name" placeholder="请输入绑定用户名" />
        </el-form-item> -->

        <el-form-item v-if="!form.is_super" label="状态">
          <el-radio-group v-model="form.state">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStatus==='create'?createData():updateData()">保存</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

	</div>
</template>

<script>
	import Pagination from '@/components/Pagination' // 基于el分页的二次封装
	import waves from '@/directive/waves' // waves directive

	export default {
		components: { Pagination },
		directives: { waves },
		data() {
			return {
        // 数据列表
        listLoading: true,
        listTotal: 0,
        isPage: false,
        tableList: [],
        multipleSelection: [],//多选数据
        // 添加/编辑弹窗
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
        	update: '编辑',
        	create: '添加'
        },
        //键字段
        keyName: 'id',
        apiPath: 'admin.admin',
        apiPath1: 'admin.department',
        apiPath2: 'admin.duties',
        apiPath3: 'admin.groups',
        apiPath4: 'cms.unit',

        // 搜索数据
        queryList: {
          page: this.$store.state.settings.page, // 每页显示数量
          curpage: 1, // 当前页码
          real_name:'',
          mobile:'',
          email:'',
          unit_id: null,
          dep_id:'',
					duties_id: '',
          groups_id: '',
          state: null,
          member_id: '',
          member_name: '',
          is_member: null
        },

        // 表单数据
        form: {
          id: 0,
          real_name:'',  //姓名
          unit_id: '',
          dep_id:'',
          duties_id: '',
          groups_id: '',
          mobile: '',    //手机
          password: '',  //登录密码
          email: '',     //邮箱
          qq: '',     //qq
          is_receive_remind: 1, //是否接收信息提醒
          member_id: '',     //绑定用户ID
          member_name: '',     //绑定用户名
          state: 1,     //状态
          is_super: 0,
        },
        formReset: {
          id: 0,
          real_name:'',  //姓名
          unit_id: '',
          dep_id:'',
          duties_id: '',
          groups_id: '',
          mobile: '',    //手机
          password: '',  //登录密码
          email: '',     //邮箱
          qq: '',     //qq
          is_receive_remind: 1, //是否接收信息提醒
          member_id: '',     //绑定用户ID
          member_name: '',     //绑定用户名
          state: 1,     //状态
          is_super: 0,
        },
        // 验证
        rules: {
          real_name: [{ required: true, message: '请输入姓名！', trigger: 'change' }],
         // dep_id: [{ required: true, message: '请输入所属部门！', trigger: 'change' }],
          duties_id: [{ required: true, message: '请选择职位！', trigger: 'change' }],
          groups_id: [{ required: true, message: '请选择权限组！', trigger: 'change' }],
          mobile: [{ required: true, message: '请输入手机号！', trigger: 'change' }],
          password: [{ required: true, message: '请输入登录密码！', trigger: 'change' }],
        },

        //单位列表
        unitListAll: [],
        unitList: [],
        //部门列表
        departmentListAll:[],
        departmentList:[],
        // 职位列表
        dutiesListAll: [],
        dutiesList: [],
        //权限列表
        groupsListAll:[],
        groupsList:[],
			}
		},
		created() {
			//获取数据列表
			this.getList()
      //获取单位列表
      this.getUnitList()
      //获取部门列表
			this.getDepartmentList()
      //获取职位列表
			this.getDutiesList()
      //获取权限组
			this.getGroupsList()
		},
		methods: {
      //获取单位列表
      getUnitList() {
      	this.$api.fetchList({}, this.apiPath4).then((response) => {
      		this.unitList = JSON.parse(JSON.stringify(response.list))
      		response.list.unshift({
      			id: '0',
      			name: '全部单位'
      		})
      		this.unitListAll = response.list
      	})
      },
      //获取部门列表
      getDepartmentList() {
      	this.$api.fetchList({}, this.apiPath1).then((response) => {
      		this.departmentList = JSON.parse(JSON.stringify(response.list))
      		response.list.unshift({
      			id: '0',
      			name: '全部部门'
      		})
      		this.departmentListAll = response.list
      	})
      },
      //获取职位列表
      getDutiesList() {
      	this.$api.fetchList({}, this.apiPath2).then((response) => {
      		this.dutiesList = JSON.parse(JSON.stringify(response.list))
      		response.list.unshift({
      			id: '0',
      			name: '全部职位'
      		})
      		this.dutiesListAll = response.list
      	})
      },
      //获取权限组列表
      getGroupsList() {
      	this.$api.fetchList({}, this.apiPath3).then((response) => {
      		this.groupsList = JSON.parse(JSON.stringify(response.list))
      		response.list.unshift({
      			id: '0',
      			name: '全部权限'
      		})
      		this.groupsListAll = response.list
      	})
      },

      // 搜索
      handleFilter() {
      	this.queryList.curpage = 1
      	this.tableList = []
        this.listTotal = 0
      	this.getList()
      },
      // 列表选择
      handleSelectionChange(val) {
      	this.multipleSelection = val
      },
      // 重置form
      resetForm() {
      	this.form = JSON.parse(JSON.stringify(this.formReset))
      },
      // 获取数据列表
      getList() {
      	this.listLoading = true
      	this.$api.fetchList(this.queryList, this.apiPath).then(response => {
      		this.tableList = response.list
      		this.listTotal = response.list_count
      		this.isPage = response.is_page
          this.listLoading = false
      	})
      },
      // 添加
      handleAdd() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 编辑
      handleEdit(id = 0) {
        this.resetForm()
        // 获取详情
        this.$api.getDetail({ id: id }, this.apiPath).then(response => {
          //数据处理
          for(let key in this.form){
            if(response.detail.hasOwnProperty(key)){
              this.form[key] = response.detail[key]
            }
          }
        })
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        })
      },
      // 添加-数据提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.add(this.form, this.apiPath).then(() => {
              // 重新获取列表
              this.queryList.curpage = 1
              this.tableList = []
              this.getList()

              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 编辑-数据提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.edit(this.form, this.apiPath).then(response => {
              // 重新获取列表
              this.getList()

              this.dialogFormVisible = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 删除
      handleDelete(id = 0) {
        let current = this
        let id_str = ''
        if (!id) {
          // 多选
          if (!this.multipleSelection.length) {
            this.$message({
              message: '请选择删除的条目！',
              type: 'warning'
            })
            return false
          }
          // 数据处理
          this.multipleSelection.forEach(item => {
            id_str += item[current.keyName] + ','
          })
        } else {
          id_str = id
        }

        // 提交数据
        this.$confirm('确认删除数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.del({ id_str: id_str }, this.apiPath).then(response => {
            // 重新获取列表
            this.getList()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
			//启用
			handleShow(id = 0) {
				this.$confirm('确认启用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.show({ id_str: id }, this.apiPath).then(response => {
						// 重新获取列表
						this.getList()
						this.$message({
							message: '启用成功',
							type: 'success'
						})
					})
				})
			},
			//禁用
			handleUpshow(id = 0) {
				this.$confirm('确认禁用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.upshow({ id_str: id }, this.apiPath).then(response => {
						// 重新获取列表
						this.getList()
						this.$message({
							message: '禁用成功',
							type: 'success'
						})
					})
				})
			}

		}
	}
</script>
